package cn.cl.service;

import cn.cl.pojo.Content;
import cn.cl.utils.HtmlParseUtil;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 标题：
 * 作者：何处是归程
 * 时间：2020/4/12 - 20:16
 */
@Service
public class ContentService {
	@Autowired
	private RestHighLevelClient restHighLevelClient;

	/**
	 * 解析数据放入es索引中
	 */
	public Boolean parseContent(String keywirds) {
		try {
			List<Content> contentList = new HtmlParseUtil().parseJD(keywirds);
			// 把查询到的数据放入 es 中
			BulkRequest bulkRequest = new BulkRequest();
			bulkRequest.timeout(TimeValue.timeValueSeconds(60));
			for (int i = 0; i < contentList.size(); i++) {
				bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(contentList.get(i)), XContentType.JSON));
			}
			BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
			return !bulkItemResponses.hasFailures();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 获取这些数据实现搜索功能
	 */
	public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) {
		try {
			if (pageNo <= 0) {
				pageNo = 1;
			}
			if (pageSize <= 0) {
				pageSize = 8;
			}
			// 条件搜索
			SearchRequest searchRequest = new SearchRequest("jd_goods");
			SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
			// 精准匹配
			TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
			searchSourceBuilder.query(termQueryBuilder);
			// 分页
			searchSourceBuilder.from(pageNo);
			searchSourceBuilder.size(pageSize);
			// 高亮
			HighlightBuilder highlightBuilder = new HighlightBuilder();
			highlightBuilder.field("title"); // 高亮的字段
			highlightBuilder.requireFieldMatch(false); // 只高亮一次
			highlightBuilder.preTags("<b style='color:red'>");
			highlightBuilder.postTags("</b>");
			searchSourceBuilder.highlighter(highlightBuilder);
			// 最大等待时间
			searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));
			// 执行搜索
			searchRequest.source(searchSourceBuilder);
			SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
			// 解析结果
			ArrayList<Map<String, Object>> result = new ArrayList<>();
			for (SearchHit hit : searchResponse.getHits().getHits()) {
				// 解析高亮的字段
				Map<String, HighlightField> highlightFields = hit.getHighlightFields();
				HighlightField title = highlightFields.get("title");
				Map<String, Object> sourceAsMap = hit.getSourceAsMap(); // 原来的结果
				// 将原来的字段替换为高亮字段
				if (title != null) {
					Text[] fragments = title.fragments();
					StringBuffer newTitle = new StringBuffer();
					for (Text text : fragments) {
						newTitle.append(text);
					}
					sourceAsMap.put("title", newTitle.toString());
				}
				result.add(sourceAsMap);
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
